<template>
  <div>
    <el-dialog
      :title="editTitle"
      :visible.sync="scheduledTasksVisible"
      width="30%"
      append-to-body
      :before-close="handleClose1"
    >
      <el-form ref="dialogForm" :model="formData">
        <el-form-item
          prop="scheduleName"
          label="任务名称："
          :rules="[
            { required: true, message: '请输入任务名称', trigger: 'blur' },
          ]"
        >
          <el-input v-model.trim="formData.scheduleName" clearable />
        </el-form-item>
        <el-form-item
          prop="scheduleEnName"
          label="任务英文名："
          :rules="[
            {
              required: true,
              pattern: /^[A-Z]{1}[A-Za-z]+$/g,
              message: '请输入任务英文名，必须是英文并且首字母大写',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model.trim="formData.scheduleEnName"
            :disabled="!!editDate"
            clearable
            placeholder="请输入任务英文名，必须是英文并且首字母大写"
          />
        </el-form-item>
        <el-form-item prop="loopType" label="循环方式：" required>
          <el-select v-model="formData.loopType" @change="handleChange">
            <el-option
              v-for="item in loopLists"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div class="temnClass" v-if="formData.loopType == 0">
          <el-form-item
            prop="params.fixCount"
            label="执行间隔："
            :rules="[
              {
                required: true,
                message: '请输入正整数的执行间隔',
                trigger: 'blur',
              },
            ]"
          >
            <div class="flexClass">
              每隔<el-input
                v-model.trim="formData.params.fixCount"
                @input="
                  (value) =>
                    (formData.params.fixCount = value
                      ? value[0].replace(/[^1-9]/g, '') +
                        value.slice(1).replace(/[^0-9]/g, '')
                      : '')
                "
                clearable
                placeholder="请输入正整数"
                style="width: 100px"
              />
              <el-select v-model="formData.params.fixUnit" style="width: 180px">
                <el-option
                  v-for="item in shijianLists"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              执行一次
            </div>
          </el-form-item>
        </div>
        <el-form-item
          prop="params.cornValue"
          label="corn表达式："
          :rules="[
            { required: true, message: '请输入corn表达式', trigger: 'blur' },
          ]"
          v-else
        >
          <el-input v-model.trim="formData.params.cornValue" clearable />
        </el-form-item>
        <el-form-item
          prop="schedule_TaskRunnable"
          label="执行的流程："
          :rules="[
            {
              required: true,
              message: '请选择执行的流程',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <myElAutocomplete
            :form="formData"
            attributeName="schedule_TaskRunnable"
            :seleteLists="serviceLists"
            valuekey="Label_Desc"
            @inputEvent="
              (val) =>
                handleBASICstrparam(
                  val,
                  serviceLists,
                  formData,
                  'scheduleTaskRunnable'
                )
            "
            :isInput="false"
            placeholder="请选择执行的流程"
          />
        </el-form-item>
        <el-form-item
          prop="moduleId"
          label="选择子项目"
          :rules="[
            {
              required: true,
              message: '选择子项目',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            v-model="formData.moduleId"
            placeholder="选择子项目"
            @change="handleChildChange"
          >
            <el-option
              v-for="item in moduleLists"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="packageName"
          label="选择模块"
          :rules="[
            {
              required: true,
              message: '请选择模块',
              trigger: 'change',
            },
          ]"
        >
          <el-select v-model="formData.packageName" placeholder="请选择模块">
            <el-option
              v-for="item in packageLists"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  voClassNameExist,
  scheduleLoopTask,
  listModulePackage,
  findclassbyType,
  projectManageprojectModellist,
} from "@/api/lowcode";
import myElAutocomplete from "../commonComponents/myElAutocomplete.vue";
export default {
  components: { myElAutocomplete },
  props: {
    scheduledTasksVisible: {
      type: Boolean,
      default: false,
    },
    editDate: {
      type: Object,
      default: null,
    },
  },
  inject: ["moduleModetTreeList"],
  data() {
    return {
      editTitle: "添加周期性定时任务",
      formData: {
        packageName: "",
        schedule_TaskRunnable: "",
        projectId: +sessionStorage.getItem("developLowCodeId"),
        scheduleEnName: "",
        loopType: "0",
        params: {
          fixUnit: "DAYS",
          fixCount: "1",
        },
        moduleId: "",
      },
      packageLists: [],
      loopLists: [
        {
          value: "0",
          label: "指定间隔",
        },
        {
          value: "1",
          label: "corn表达式",
        },
      ],
      shijianLists: [
        {
          value: "DAYS",
          label: "日",
        },
        {
          value: "HOURS",
          label: "时",
        },
        {
          value: "MINUTES",
          label: "分",
        },
        {
          value: "SECONDS",
          label: "秒",
        },
      ],
      serviceLists: [],
      moduleLists: [],
    };
  },
  async created() {
    await this.findclassbyType();
    await this.projectManageprojectModellist();
    if (this.editDate) {
      this.formData = this.editDate;
      const obj = this.serviceLists.find(
        (v) => v.className === this.formData.scheduleTaskRunnable
      );
      if (obj) {
        this.$set(this.formData, "schedule_TaskRunnable", obj.Label_Desc);
      } else {
        this.$set(this.formData, "schedule_TaskRunnable", "");
      }
      this.editTitle = "周期性定时任务编辑";
    } else {
      this.editTitle = "添加周期性定时任务";
      this.formData.moduleId = this.moduleLists[0]?.id;
    }
    this.listModulePackage();
  },
  methods: {
    handleChildChange() {
      this.formData.packageName = "";
      this.listModulePackage();
    },
    async projectManageprojectModellist() {
      this.moduleLists = [];
      const res = await projectManageprojectModellist(
        +sessionStorage.getItem("developLowCodeId")
      );
      if (res?.code === 200) {
        this.moduleLists = res.data;
      }
    },
    handleBASICstrparam(val, lists, item, param) {
      const obj = lists.find((v) => v.Label_Desc === val);
      if (obj) {
        item[param] = obj.className;
      } else {
        item[param] = "";
      }
    },
    async listModulePackage() {
      this.packageLists = [];
      const res = await listModulePackage(
        +sessionStorage.getItem("developLowCodeId"),
        this.formData.moduleId
      );
      if (res?.code === 200) {
        this.packageLists = res.data;
      }
    },
    async findclassbyType() {
      this.serviceLists = [];
      const res = await findclassbyType(
        +sessionStorage.getItem("developLowCodeId")
      );
      if (res?.code == 200) {
        this.serviceLists = res.data;
        this.serviceLists.forEach((item) => {
          this.$set(
            item,
            "Label_Desc",
            item.classDesc
              ? `${item.className} | ${item.classDesc}`
              : item.className
          );
        });
      }
    },
    handleChange(val) {
      if (val == 0) {
        this.formData.params = {
          fixUnit: "DAYS",
          fixCount: "1",
        };
      } else {
        this.formData.params = {
          cornValue: "",
        };
      }
    },
    handleClose1() {
      this.$emit("close");
    },
    async handleBlur(name, id) {
      const res = await voClassNameExist(name, id);
      if (res?.code === 200) {
        if (res.data) {
          this.$message({
            message: "任务英文名已存在，请从新输入",
            type: "warning",
            showClose: true,
          });
          this.formData.scheduleEnName = "";
          return true;
        }
      }
    },
    handleSave() {
      this.$refs["dialogForm"].validate(async (valid) => {
        if (valid) {
          console.log(!this.editDate, 44444444444444);
          if (!this.editDate) {
            const flag = await this.handleBlur(
              this.formData.scheduleEnName,
              +sessionStorage.getItem("developLowCodeId")
            );
            if (flag) return;
          }
          const form_Data = JSON.parse(JSON.stringify(this.formData));
          const res = await scheduleLoopTask(form_Data);
          if (res?.code === 200) {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.handleClose1();
            if (!this.editDate) {
              this.$parent.currentComponent = "basicsssssComponents";
              await this.moduleModetTreeList();
              this.$parent.fengzhuangConent(res.data);
              this.$parent.treeGaoliangAndscroll(res.data);
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.temnClass {
  ::v-deep label {
    margin-top: 3px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 10px !important;
  }
  .flexClass {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
